package net.xdclass.service.impl;

import net.xdclass.common.LinkSafetyRules;
import net.xdclass.service.CustomRulesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;

/**
 * @author 小二
 */
@Service
public class CustomRulesServiceImpl implements CustomRulesService {

    @Autowired
    private LinkSafetyRules rules;

    @Override
    public CompletableFuture<Boolean> detect(String url) {
        return CompletableFuture.supplyAsync(() -> {
            // 关键词匹配
            if (rules.getKeywords().contains(url)) {
                return true;
            }

            // 正则表达式匹配
            for (String pattern : rules.getRegex()) {
                if (url.matches(pattern)) {
                    return true;
                }
            }

            // 黑名单域名匹配
            if (rules.getBlacklist().stream().anyMatch(url::contains)) {
                return true;
            }

            // URL长度检测
            return url.length() > rules.getMaxUrlLength();
        });
    }
}
